import getUserTempId from "@/utils/userTempId"

import {
    requestLogin,
    requestUserInfo,
    requestLogout
} from "@/api"

//配置用户信息模块模块
const state = {
    userTempId: getUserTempId(),
    token: localStorage.getItem("user_token") || "",
    nickName: "",
}

const mutations = {
    //登录
    SET_LOGIN_STATE(state , value){
        state.token = value
    },

    SET_USERINFO_STATE(state , value){
        state.nickName = value
    },

    SET_LOGOUT_STATE(state){
        state.token = "",
        state.nickName = "",
        localStorage.removeItem("user_token")
    }

}
const actions = {
    //登录
    async userLogin({commit}, userInfo){
        const result = await requestLogin(userInfo)
        commit("SET_LOGIN_STATE" , result.token)
        //数据持久化
        localStorage.setItem("user_token" , result.token)
    },

    //请求用户名
    async getUserInfo({commit}){
        //token失效请求用户名失败
        try {
            console.log("开始请求用户名");
            const result = await requestUserInfo()
            commit("SET_USERINFO_STATE" , result.nickName)
        } catch (error) {
            console.log("请求用户名失败");
            //请求用户名失败进catch，删除token
            localStorage.removeItem("user_token")
            return Promise.reject()
        }
    },

    //退出登录
    async userLogout({commit}){
        await requestLogout()
        commit("SET_LOGOUT_STATE")
    }


}
const getters = {}

//暴露模块
export default {
    //开启命名空间
    namespaced: true,
    state,
    mutations,
    actions,
    getters,
}